package com.whsxt.controller;

import com.github.pagehelper.PageInfo;
import com.whsxt.common.AjaxResult;
import com.whsxt.domain.Customer;
import com.whsxt.dto.CustomerDto;
import com.whsxt.service.CustomerService;
import com.whsxt.utils.Result2DTreeVoUtils;
import com.whsxt.vo.DropDownVo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/customer")
@RequiresRoles(value = {"business", "admin"}, logical = Logical.OR)
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    /**
     * 获取分页数据
     * @param customerDto
     * @return
     */
    @RequestMapping("/findByPage.do")
    public AjaxResult findByPage(CustomerDto customerDto){
        PageInfo<Customer> pageInfo = customerService.findByPage(customerDto);
        return AjaxResult.ok(pageInfo);
    }

    /**
     * 添加客户数据
     * @param customerDto
     * @return
     */
    @RequestMapping("/add.do")
    @RequiresPermissions(value = {"customer:add"})
    public AjaxResult add(CustomerDto customerDto){
        boolean isOk = customerService.save(customerDto);
        return isOk ? AjaxResult.ok() : AjaxResult.error("添加客户数据失败");
    }

    /**
     * 删除客户数据
     * @param id
     * @return
     */
    @RequestMapping("/delete.do")
    @RequiresPermissions(value = {"customer:delete"})
    public AjaxResult delete(Integer[] id){
        boolean isOk = customerService.batchRemove(Arrays.asList(id));
        return isOk? AjaxResult.ok() : AjaxResult.error("删除数据失败");
    }

    @RequestMapping("/update.do")
    @RequiresPermissions(value = {"customer:update"})
    public AjaxResult update(CustomerDto customerDto){
        boolean isOk = customerService.update(customerDto);
        return isOk? AjaxResult.ok() : AjaxResult.error("修改客户数据失败");
    }

    /**
     * 查询所有的客户数据转化为DropDownVo对象
     * @return
     */
    @RequestMapping("/getAllCustomer.do")
    public AjaxResult getAllCustomer(){

        List<Customer> customerList = customerService.selectAll();
        List<DropDownVo> dropDownVoList = Result2DTreeVoUtils.customerList2DropDownVoList(customerList);
        return AjaxResult.ok(dropDownVoList);
    }
}
